package com.gzdh.tang.modu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.WebUtils;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.gzdh.tang.comm.vo.Result;
import com.gzdh.tang.config.ali.AliPayUtil;
import com.gzdh.tang.modu.mapper.MPublicMapper;
import com.gzdh.tang.modu.model.AliPayResultVo;
import com.gzdh.tang.modu.model.WithholdReq;
import com.gzdh.tang.modu.model.dk.JsonsRootBean;
import com.gzdh.tang.modu.util.CloudSaleApiUtil;
import com.gzdh.tang.qimei.util.ByteUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Random;

import sun.misc.BASE64Decoder;

@Slf4j
@RequestMapping("api/test")
@RestController
public class TestController {

    @Autowired
    MPublicMapper mPublicMapper;

    @PostMapping("/base64Upload")
    public Result<Object> base64Upload(@RequestParam("base64Data") String base64Data,
                                       @RequestParam(value = "bizPath", required = false) String bizPath,
                                       @RequestParam(value = "name", required = false) String name) {
        Result<Object> result = new Result<>();
        log.info("==上传图片==");
        log.info("==接收到的数据==" + base64Data);
        String ctxPath = "D:/";
        String fileName = null;
        String dataPrix = ""; //base64格式前头
        String data = "";//实体部分数据
        if (base64Data == null || "".equals(base64Data)) {
            return Result.error("上传失败，上传图片数据为空");
        } else {
            String[] d = base64Data.split("base64,");//将字符串分成数组
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                return Result.error(401, "上传失败，数据不合法");
            }
        }
        String suffix = "";//图片后缀，用以识别哪种格式数据
        //编码的jpeg图片数据
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
            suffix = ".jpg";
        } else if ("data:image/jpg;".equalsIgnoreCase(dataPrix)) {
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
            //编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
            //编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
            //编码的png图片数据
            suffix = ".png";
        } else {
            return Result.error("上传图片格式不合法");
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(data);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    //调整异常数据
                    b[i] += 256;
                }
            }
            String filePath = "";
            if (bizPath != null) {
                filePath = ctxPath + File.separator + bizPath + File.separator;
            } else {
                filePath = ctxPath + File.separator;
            }
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            Random r = new Random(1);
            String orgName = String.valueOf(r.nextInt(100));
//            orgName = CommonUtils.getFileName(orgName);
//            if (orgName.indexOf(".") != -1) {
            if (name != null) {
                fileName = name;
            } else {
                fileName = orgName + "_" + System.currentTimeMillis()
                        + suffix;
            }

//            } else {
//                fileName = orgName + "_" + System.currentTimeMillis();
//            }
            String savePath = file.getPath() + File.separator + fileName;
            OutputStream out = new FileOutputStream(savePath);
            out.write(b);
            out.flush();
            out.close();
//            String imgurl=fileName;
            //imageService.save(imgurl);
            return Result.ok(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("上传图片失败");
        }

    }

    /**
     * 支付宝的测试
     *
     * @return
     */
    @GetMapping("aliPay")
    public Result<Object> aliPya(@RequestParam("orders") String orders, @RequestParam("orderPrice") String orderPrice,
                                 @RequestParam("authCode") String authCode, @RequestParam("terminalParams") String terminalParams) {
        Result<Object> result = new Result<>();
        try {

            havePost(orders, orderPrice, authCode, terminalParams);

//            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
//                    AliPayUtil.getAppid(), AliPayUtil.getPrivateKey(),
//                    "json", "GBK", AliPayUtil.getPublicKey(),
//                    "RSA2");
//            AlipayTradePayRequest request = new AlipayTradePayRequest();
//            JSONObject bizContent = new JSONObject();
//            bizContent.put("out_trade_no", String.valueOf(System.currentTimeMillis()));
//            bizContent.put("total_amount", "0.03");
//            bizContent.put("subject", "人脸消费机");
//            bizContent.put("product_code", "GENERAL_WITHHOLDING");//产品码
//            bizContent.put("timeout_express", "1d");
////            bizContent.put("scene","security_code");
//            bizContent.put("auth_code", "AAAAHAgBAQEAAAJsB/jXiQAHawZmy0ICAAABhD0aZ2EAA/SAQQRPnBetaBjxPVXoeR2/cdAs5h+vti8nsy/8jfM+Icd3+pA3ac/A+Qni/e8y3iKqWdsG0OMJxWw5NkqaZOhg2DB6QKPx5Nrlw2RZWAeUZ+HXgLxM3lu0gjeusLZIlrJKqmlNEKFQhsMfupLimHmvboVQ2bsjpFMWNF+XjUg08wABjXwAAAAAC7gAAACBHn9mcDRfVFU5SFIwdE9UVTVLU1UxSlRVbE9TU0JPU1VsSVNrcFBSMGRPU1VkSklFMVBSMGRQVDA5UFNFcEtTMGhPVEVjZ1NFaFBIVWRHU2trYVNVWWFTMGRIVHgxSUhVNUlHUjBlR2t3YUhVaExTMDVPU0UxSlNFOUpUVTlPSUU4AAABhEHHJ5hA0YqPwv8nrfTKgiSR1I01eqnBY7fXLIUx7rXgMZ7xCPTBXr/gUaLAzaSOQgVuqOQZFUswM5zAlS6BnBB6g98grw==");
//            JSONObject business_params = new JSONObject();
//            business_params.put("assignJointAccountId", "2088420029171855");
//            business_params.put("enterprisePayAmount", "0.01");
//            bizContent.put("business_params", business_params);
//
//            JSONObject extend_params = new JSONObject();
//            extend_params.put("pdSubBizScene", "enterprisePay");
//            bizContent.put("extend_params", extend_params);
//
//            JSONArray query_options = new JSONArray();
//            query_options.add("enterprise_pay_info");
//            bizContent.put("query_options", query_options);
//
//            JSONObject asset_name = new JSONObject();
//            asset_name.put("asset_name", "enterprisePay");
//
//            JSONObject priority_pay_assets = new JSONObject();
//
//            JSONArray assets_list = new JSONArray();
//            assets_list.add(asset_name);
//            priority_pay_assets.put("assets_list", assets_list);
//            bizContent.put("priority_pay_assets", priority_pay_assets);
//
//
//            JSONObject agreement_no = new JSONObject();
//            agreement_no.put("agreement_no", "20225904888708444661");
//
//            bizContent.put("agreement_params", agreement_no);

//            request.setBizContent(bizContent.toString());
//            System.out.println("请求参数：" + bizContent.toString());

//            JsonsRootBean jsonsRootBean = new JsonsRootBean(String.valueOf(System.currentTimeMillis()), "0.02",
//                    "AAAAHAgBAQEAAAJsB/jXiQAHawZmy0ICAAABhD0aZ2EAA/SAQQRPnBetaBjxPVXoeR2/cdAs5h+vti8nsy/8jfM+Icd3+pA3ac/A+Qni/e8y3iKqWdsG0OMJxWw5NkqaZOhg2DB6QKPx5Nrlw2RZWAeUZ+HXgLxM3lu0gjeusLZIlrJKqmlNEKFQhsMfupLimHmvboVQ2bsjpFMWNF+XjUg08wABjXwAAAAAC7gAAACBHn9mcDRfVFU5SFIwdE9UVTVLU1UxSlRVbE9TU0JPU1VsSVNrcFBSMGRPU1VkSklFMVBSMGRQVDA5UFNFcEtTMGhPVEVjZ1NFaFBIVWRHU2trYVNVWWFTMGRIVHgxSUhVNUlHUjBlR2t3YUhVaExTMDVPU0UxSlNFOUpUVTlPSUU4AAABhEHHJ5hA0YqPwv8nrfTKgiSR1I01eqnBY7fXLIUx7rXgMZ7xCPTBXr/gUaLAzaSOQgVuqOQZFUswM5zAlS6BnBB6g98grw==",
//                    "20225904888708444661", "2088420029171855", "0.02","");
//            System.out.println("请求参数2：" + JSONObject.toJSONString(jsonsRootBean));
//            request.setBizContent(JSONObject.toJSONString(jsonsRootBean));
//            AlipayTradePayResponse response = alipayClient.execute(request, null, AliPayUtil.getAppAuthToken());
//            if (response.isSuccess()) {
//                System.out.println("调用成功");
//
//            } else {
//
//                System.out.println("调用失败");
//            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("zhuanhuanTest")
    public Result<Object> zhuanhuanTest() {
        Result<Object> result = new Result<>();
        List<Map<String, String>> mapList = mPublicMapper.getOldryxx();
        for (int i = 0; i < mapList.size(); i++) {
            String userId = mapList.get(i).get("UserId");
            String cardSn = mapList.get(i).get("cardsn");
//            System.out.println("获取用户：" + userId + "\t10进制cardsn：" + cardSn );

            byte[] cardsnByte = ByteUtil.intToBytes2(Integer.parseUnsignedInt(cardSn));
//            System.out.println("获取用户：" + userId + "\t10进制cardsn：" + cardSn + "\t转换后的cardsn：" + ByteUtil.bytesToHexString(cardsnByte));
            mPublicMapper.updateOldryxx(ByteUtil.bytesToHexString(cardsnByte).toUpperCase(),userId);
        }
//        byte[] cardsnByte = ByteUtil.intToBytes2(Integer.parseUnsignedInt("2894629388"));
//        System.out.println("转："+ByteUtil.bytesToHexString(cardsnByte));

        return result;
    }

    private boolean havePost(String orders, String orderPrice,
                             String authCode, String terminalParams) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                    AliPayUtil.getAppid(), AliPayUtil.getPrivateKey(),
                    "json", "GBK", AliPayUtil.getPublicKey(),
                    "RSA2");
            AlipayTradePayRequest request = new AlipayTradePayRequest();
            JsonsRootBean jsonsRootBean;

            jsonsRootBean = new JsonsRootBean(orders, orderPrice,
                    authCode, terminalParams, "");
            request.setBizContent(JSONObject.toJSONString(jsonsRootBean));
            AlipayTradePayResponse response = alipayClient.execute(request, null, AliPayUtil.getAppAuthToken());
            if (response.isSuccess()) {
                System.out.println("调用成功");
                return true;
            } else {
                System.out.println("调用失败");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
